package com.oromwin.repos.http.handler;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class TestHandler implements HttpHandler {
    
    @Override
    public void handle(HttpExchange h) throws IOException {
        int totalBytes = 0;
        {
            File f = new File("./filename");
            OutputStream os = new FileOutputStream(f);
            BufferedInputStream bis = new BufferedInputStream(h.getRequestBody());
            int chunkSize = 4096;
            byte[] b = new byte[chunkSize];
            int bytesRead = 0;
            while ((bytesRead = bis.read(b)) > 0) {
                os.write(b, 0, bytesRead);
                totalBytes += bytesRead;
            }
            os.close();
        }
        try {
            String response = "OK";
            byte[] responseBytes = response.getBytes("utf-8");
            h.getResponseHeaders().set("Content-Type", "text/plain"); // http://en.wikipedia.org/wiki/Internet_media_type
            h.sendResponseHeaders(200, responseBytes.length);
            OutputStream os = h.getResponseBody();
            os.write(responseBytes);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
